//
//  MusicViewController.m
//  LO_MUSIC
//
//  Created by 徐强 on 16/2/24.
//  Copyright © 2016年 徐强. All rights reserved.
//
/*
 
 1. 线程块(自定义线程)
 
 
 2. 图片下载
 
 1> 先检查缓存有没有图片
 2> 检查一下是否正在下载
 3> 去下载,
 4> 下载完成,展示出来,存到缓存中

 3. 滑动不加载 + sdwebimage
 
	if (滑动) {
 if (本地有图片) {
 加载本地图片 sd
 } else {
 加载占位图
 }
	} else {
	// 加载图片 sd
	}
 
 //  滑动结束,减速结束
 {
 // 获取当前可视的indexPath
 // 刷新可视区域
 }

 
 */
#import "MusicViewController.h"
#import "RequestUrl.h"
#import "DownLoadImageOperation.h"
#import "MusicPlayViewController.h"
@interface MusicViewController ()<UITableViewDataSource,UITableViewDelegate,DownLoadImageOperationDelegate>

@property (nonatomic,strong)UITableView *tableView;
///模型数组
@property (nonatomic, strong)NSArray *arrAlData;
///队列
@property (nonatomic, strong)NSOperationQueue *queue;
///存放图片的url
@property (nonatomic , strong)NSMutableDictionary *imageDic;
//防止已经在队列中的任务再加入队列中
@property (nonatomic , strong)NSMutableDictionary *operationdic;
//音乐播放详情界面
@property (nonatomic,strong)MusicPlayViewController *musicVC;
////判断是否正在滑动
//@property(nonatomic,assign,getter=isScrolling)BOOL scrolling;

@end


@implementation MusicViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:(UITableViewStyleGrouped)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    [self.view addSubview:self.tableView];
    
    //请求数据
    RequestUrl *request = [RequestUrl shareRequestUrl];
    __weak typeof(self) weakSelf = self;
    [request requestMusicWithSuccess:^(id item) {
        
        weakSelf.arrAlData = item;
        [weakSelf.tableView reloadData];
    } fail:^(NSError *error) {
        
        NSLog(@"%@",error);
        
    }];
    
    //导航栏添加一个跳转按钮
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"播放音乐" style:(UIBarButtonItemStylePlain) target:self action:@selector(rightAction)];
    self.navigationItem.rightBarButtonItem = right;

}
//点击“播放音乐”按钮跳转到播放界面
- (void)rightAction{
    self.musicVC = [MusicPlayViewController shareMusicPlayViewController];
    [self.navigationController pushViewController:self.musicVC animated:YES ];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrAlData.count;
}
//cell出现在屏幕时会走的方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_music"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"cell_music"];
    }
    MusicModel *model = self.arrAlData[indexPath.row];
    cell.textLabel.text = model.name;
    cell.detailTextLabel.text = model.singer;
    //先去字典中查找
    if ([self.imageDic.allKeys containsObject:model.picUrl]) {
        //字典中已经存在需要的图片
        cell.imageView.image = self.imageDic[model.picUrl];
    }else{
        
        //占位图片
        cell.imageView.image = [UIImage imageNamed:@"23.jpg"];
        if(self.tableView.dragging || self.tableView.decelerating){
            //如果正在滑动，不处理图片
            return cell;
        }
        //判断是不是已经在下载
        if([self.operationdic.allKeys containsObject:model.picUrl]){
            //正在下载
        }else{
        //没有下载
        //初始化自定义线程块
        DownLoadImageOperation *downImage = [[DownLoadImageOperation alloc]init];
        downImage.url = model.picUrl;
        downImage.delegate = self;
        downImage.indexPath = indexPath;
        //添加到队列
        [self.queue addOperation:downImage];
            
            [self.operationdic setValue:downImage forKey:model.picUrl];
        }
    }
    
    return cell;
}
//滑动结束后加载
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (!decelerate) {
        [self loadImage];
    }
}
//结束减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self loadImage];
}
- (void)loadImage{
    //取出当前可视的cell
    NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
    //刷新界面的cell
    [self.tableView reloadRowsAtIndexPaths:visiblePaths withRowAnimation:(UITableViewRowAnimationNone)];
}

//downImagedelegate
- (void)getImage:(UIImage *)image operation:(DownLoadImageOperation *)operation{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:operation.indexPath];
    cell.imageView.image = image;
    //往字典里添加下载过的图片
    [self.imageDic setValue:image forKey:operation.url];
    //下载结束后从队列字典中删除已经下载的任务
    [self.operationdic removeObjectForKey:operation.url];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}
//点击cell进行页面跳转以及属性传值
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   self.musicVC = [MusicPlayViewController shareMusicPlayViewController];
   self.musicVC.index = indexPath.row;
    self.musicVC.arrAllMusic = self.arrAlData;
    [self.navigationController pushViewController:self.musicVC animated:YES ];
    
}

#pragma mark - 懒加载
- (NSOperationQueue *)queue{
    
    if (!_queue) {
        _queue =[[NSOperationQueue alloc]init];
        _queue.maxConcurrentOperationCount = 3;//最大并发数：3个同时下
    }
    return _queue;
}
- (NSMutableDictionary *)imageDic{
    if (!_imageDic ) {
        _imageDic = [NSMutableDictionary dictionary];
    }
    return _imageDic;
}
- (NSMutableDictionary *)operationdic{
    if (!_operationdic ) {
        _operationdic = [NSMutableDictionary dictionary];
    }
    return _operationdic;
}

@end
